import axios from "axios";
import { ElMessage as message } from 'element-plus';

// create an axios instance
const baseURL = import.meta.env.MODE == "development" ? import.meta.env.VITE_VUE_BASE_URL : globalParams.api;
const service = axios.create({
  baseURL: baseURL, 
  timeout: 20000,
});

//response interceptor 返回拦截器
service.interceptors.response.use(
  response => {
    const res = response.data
    //接口返回值ret为0成功
    if(response.config.url.includes('/customService/downloadFile')){
      return res
    }
    if(res.code !== 0){
      message.error(res.msg || 'Error')
      return Promise.reject(new Error(res.message || 'Error'))
    }else{
      return res
    }
  },
  error => {
    console.log('err' + error)
    message.error(error.msg)
    return Promise.reject(error)
  }
)

//文件下载
export function download (fid) {
  return service({
    url: `/customService/downloadFile.do?fileId=${fid}&${Math.random()}`,
    method: 'get',
  })
}

//文件地址
export function downloadUrl (fid){
  return `${baseURL}/customService/downloadFile.do?fileId=${fid}`; 
}

//文件上传
export function upload (data){
  return service({
    url:'/customService/uploadFile.do',
    method:'post',
    headers: { "Content-Type": "multipart/form-data;charset=utf-8" },
    data
  })
}
